package com.legleg.run.crawler;

import com.legleg.conf.Configure;
import com.legleg.data.Album;
import com.legleg.data.Feed;
import com.legleg.handler.AlbumHandler;
import com.legleg.run.crawler.parser.BaseParser;
import com.legleg.run.crawler.parser.ParserHandler;
import com.legleg.util.BaseUtil;
import com.legleg.util.DownLoadObject;
import com.legleg.util.DownLoadUtil;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 12-12-29
 * Time: 下午2:36
 * To change this template use File | Settings | File Templates.
 */
public class FeedThread implements Runnable {
    private static final Logger logger = Logger.getLogger(FeedThread.class);
    private Feed feed;
    public FeedThread(Feed feed){
        this.feed = feed;
    }
    @Override
    public void run() {
        BaseParser parser = ParserHandler.getParser(StringUtils.trimToEmpty(feed.getFeedurl()));
        if(parser == null) return;
        List<Album> albums = parser.getAlbumUrlList(feed);
        if(albums==null || albums.size()==0) return;
        for(Album album:albums){
            if(AlbumHandler.getInstance().ifCrawled(album)) continue;

            album = parser.getAlbumDetail(album);
            List<String> piclist = album.getPicurls();
            if(piclist==null || piclist.size()==0) continue;

            long albumId = AlbumHandler.getInstance().insert(album);
            if(albumId == -1) continue;
            String albumDir = BaseUtil.getAlbumImageDir(Configure.ALBUM_IMAGE_DIR,albumId);
            int i = 0;
            for(String picurl:piclist) {
                i++;
                DownLoadObject down = new DownLoadObject();
                down.setUrl(picurl);
                down.setDir(albumDir);
                down.setRename(i+"."+ FilenameUtils.getExtension(picurl));
                boolean downret = DownLoadUtil.download(down);
                if(!downret) i--;
            }
            if(i>0) {
                //insert into db.
                album.setPicnum(i);
                album.setSuccess(1);
                AlbumHandler.getInstance().update(album);
            }
        }
        logger.info("FeedThread finished "+feed.getId()+":"+feed.getFeedurl());
    }
}
